package serverletGrade;

import Server.GradeServer;
import user.Grade;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet(name = "GradeInitServlet",urlPatterns = "/gradeinit")
public class GradeInitServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            System.out.println("获取数据中。。。");
            GradeServer gradeServer = new GradeServer();
            List<Grade> grades=null;
            String start = "0",end = "3";
            int count = gradeServer.countGradeServer();
            if(null!=(request.getParameter("start"))){
                start = request.getParameter("start");
                if(Integer.parseInt(request.getParameter("start"))>((count-1) / 3)){
                    start=Integer.toString(Integer.parseInt(request.getParameter("start"))-1);

                }else if(Integer.parseInt(request.getParameter("start"))<0){
                    start="0";
                }
                System.out.println("已经执行");
            }
            grades = gradeServer.getGradeServer(start,end);
            for (Grade grade : grades){
                grade.setPeopleNum(String.valueOf(gradeServer.countStudentServer(grade.getNum())));
                gradeServer.motifyGradeServer(grade.getNum(),grade);
            }
            grades = gradeServer.getGradeServer(start,end);
            request.getSession().setAttribute("list", grades);
            request.getSession().setAttribute("count", count);
            request.getSession().setAttribute("pagenum", ((count-1) / 3));
            request.getSession().setAttribute("start", Integer.parseInt(start));
            response.sendRedirect("Grade.jsp");
            System.out.println("数据获取完毕");
            System.out.println(grades);
            for (Grade grade : grades){
                grade.setPeopleNum(String.valueOf(gradeServer.countStudentServer(grade.getNum())));
                gradeServer.motifyGradeServer(grade.getNum(),grade);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
